const { prisma } = require('../config/prisma');

class InvitationPrisma {
  constructor(data) {
    this.id = data.id;
    this.inviter_user_id = data.inviter_user_id;
    this.invitee_user_id = data.invitee_user_id;
    this.reward_type = data.reward_type;
    this.reward_value = data.reward_value;
    this.status = data.status;
    this.created_at = data.created_at;
    
    // 关联数据
    this.inviter = data.users_invitations_inviter_user_idTousers;
    this.invitee = data.users_invitations_invitee_user_idTousers;
  }

  /**
   * 根据ID查找邀请记录
   * @param {number} id 邀请记录ID
   * @param {Object} options 查询选项
   * @returns {Promise<InvitationPrisma|null>}
   */
  static async findById(id, options = {}) {
    const { include = {} } = options;
    
    const invitation = await prisma.invitations.findUnique({
      where: { id: BigInt(id) },
      include: {
        users_invitations_inviter_user_idTousers: include.inviter || false,
        users_invitations_invitee_user_idTousers: include.invitee || false
      }
    });
    
    return invitation ? new InvitationPrisma(invitation) : null;
  }

  /**
   * 根据被邀请人ID查找邀请记录
   * @param {number} inviteeUserId 被邀请人ID
   * @param {Object} options 查询选项
   * @returns {Promise<InvitationPrisma|null>}
   */
  static async findByInviteeId(inviteeUserId, options = {}) {
    const { include = {} } = options;
    
    const invitation = await prisma.invitations.findUnique({
      where: { invitee_user_id: BigInt(inviteeUserId) },
      include: {
        users_invitations_inviter_user_idTousers: include.inviter || false,
        users_invitations_invitee_user_idTousers: include.invitee || false
      }
    });
    
    return invitation ? new InvitationPrisma(invitation) : null;
  }

  /**
   * 根据邀请人ID查找邀请记录列表
   * @param {number} inviterUserId 邀请人ID
   * @param {Object} options 查询选项
   * @returns {Promise<{invitations: InvitationPrisma[], total: number}>}
   */
  static async findByInviterId(inviterUserId, options = {}) {
    const { 
      page = 1, 
      limit = 10, 
      orderBy = { created_at: 'desc' },
      include = {}
    } = options;
    
    const skip = (page - 1) * limit;
    const where = { inviter_user_id: BigInt(inviterUserId) };
    
    const [invitations, total] = await Promise.all([
      prisma.invitations.findMany({
        where,
        orderBy,
        skip,
        take: limit,
        include: {
          users_invitations_inviter_user_idTousers: include.inviter || false,
          users_invitations_invitee_user_idTousers: include.invitee || false
        }
      }),
      prisma.invitations.count({ where })
    ]);
    
    return {
      invitations: invitations.map(invitation => new InvitationPrisma(invitation)),
      total
    };
  }

  /**
   * 创建邀请记录
   * @param {Object} invitationData 邀请数据
   * @returns {Promise<InvitationPrisma>}
   */
  static async create(invitationData) {
    const invitation = await prisma.invitations.create({
      data: {
        inviter_user_id: BigInt(invitationData.inviter_user_id),
        invitee_user_id: BigInt(invitationData.invitee_user_id),
        reward_type: invitationData.reward_type || null,
        reward_value: invitationData.reward_value || null,
        status: invitationData.status || 'unclaimed'
      },
      include: {
        users_invitations_inviter_user_idTousers: true,
        users_invitations_invitee_user_idTousers: true
      }
    });
    
    return new InvitationPrisma(invitation);
  }

  /**
   * 更新邀请记录
   * @param {number} id 邀请记录ID
   * @param {Object} updateData 更新数据
   * @returns {Promise<InvitationPrisma|null>}
   */
  static async update(id, updateData) {
    try {
      const invitation = await prisma.invitations.update({
        where: { id: BigInt(id) },
        data: updateData,
        include: {
          users_invitations_inviter_user_idTousers: true,
          users_invitations_invitee_user_idTousers: true
        }
      });
      
      return new InvitationPrisma(invitation);
    } catch (error) {
      if (error.code === 'P2025') {
        return null; // 记录不存在
      }
      throw error;
    }
  }

  /**
   * 统计邀请人的邀请数量
   * @param {number} inviterUserId 邀请人ID
   * @returns {Promise<number>}
   */
  static async countByInviterId(inviterUserId) {
    return await prisma.invitations.count({
      where: { inviter_user_id: BigInt(inviterUserId) }
    });
  }

  /**
   * 检查邀请者是否满足激活条件
   * @param {number} inviterUserId 邀请人ID
   * @param {number} requiredCount 需要的邀请数量（默认3个）
   * @returns {Promise<boolean>}
   */
  static async checkActivationCondition(inviterUserId, requiredCount = 3) {
    const count = await this.countByInviterId(inviterUserId);
    return count >= requiredCount;
  }

  /**
   * 处理邀请奖励和激活逻辑
   * @param {number} inviterUserId 邀请人ID
   * @returns {Promise<{activated: boolean, rewardGiven: boolean}>}
   */
  static async processInvitationReward(inviterUserId) {
    const UserPrisma = require('./UserPrisma');
    
    // 检查邀请者是否满足激活条件
    const shouldActivate = await this.checkActivationCondition(inviterUserId);
    
    let activated = false;
    let rewardGiven = false;
    
    if (shouldActivate) {
      // 获取邀请者信息
      const inviter = await UserPrisma.findById(inviterUserId);
      
      if (inviter && inviter.status === 'inactive') {
        // 激活邀请者账户并给予奖励条数
        await UserPrisma.update(inviterUserId, {
          status: 'active',
          publishing_credits: inviter.publishing_credits + 5 // 激活奖励5条
        });
        
        activated = true;
        rewardGiven = true;
      }
    }
    
    return { activated, rewardGiven };
  }

  /**
   * 转换为JSON对象
   * @returns {Object}
   */
  toJSON() {
    const result = {
      id: this.id?.toString(),
      inviter_user_id: this.inviter_user_id?.toString(),
      invitee_user_id: this.invitee_user_id?.toString(),
      reward_type: this.reward_type,
      reward_value: this.reward_value,
      status: this.status,
      created_at: this.created_at
    };
    
    if (this.inviter) {
      result.inviter = {
        id: this.inviter.id?.toString(),
        nickname: this.inviter.nickname,
        phone_number: this.inviter.phone_number
      };
    }
    
    if (this.invitee) {
      result.invitee = {
        id: this.invitee.id?.toString(),
        nickname: this.invitee.nickname,
        phone_number: this.invitee.phone_number
      };
    }
    
    return result;
  }
}

module.exports = InvitationPrisma;
